//
//  EFengComposeController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/1.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengComposeController.h"
#import "UIBarButtonItem+category.h"
#import "CHSCharacterCountTextView.h"
#import "CXmppRequestMgr.h"
#import "CContactModel.h"
#import "CContactMgr.h"
#import "EFComposeEmotionView.h"
#import "EFengComposeTextView.h"
#import "RIButtonItem.h"
#import "UIActionSheet+Blocks.h"
#import "QBImagePickerController.h"
#import "EFengComposePhotoView.h"
#import "MBProgressHUD+WZ.h"
#import "UIUtil.h"
#import "EFengShare.h"
#import "CShareMgr.h"
#import "SDWebImageManager.h"
#import "RIButtonItem.h"
#import "UIActionSheet+Blocks.h"
#import "EFengShareSelectDepController.h"
#import "EFengShareSelectGroupController.h"
#import "EFengShareSelectMemController.h"
#import "UIImage+Category.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import "CSharePersonMgr.h"
#import "CFolderMgr.h"
#import "UIImage+Category.h"
#import "JKAlertDialog.h"
#import "MicroDef.h"
#import "CaptureViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "SBCaptureToolKit.h"
#import "WZPlayerViewController.h"
#import "ChildHoodService.h"
#define  PHOTOWIDTH (HARDWARE_SCREEN_WIDTH - 80.0f) / 3.0f

@interface EFengComposeController ()<EFengComposeTextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, QBImagePickerControllerDelegate, EFengComposePhotoViewDelegate, EFComposeEmotionViewDelegate, UIScrollViewDelegate>

WeakProperty EFengComposeTextView *textView;
WeakProperty UIView *toolBar;

StrongProperty CContactModel *curContact;

AssignProperty BOOL isEmotionShow;

WeakProperty UIButton *emotionButton;
WeakProperty UIButton *pictureButton;
WeakProperty UIButton *quanxianButton;
WeakProperty UIButton *videoButton;
WeakProperty UIView *photosView;

StrongProperty NSMutableArray *photosArray;
WeakProperty EFComposeEmotionView *composeEmotionView;
AssignProperty NSRange selectedRange;

StrongProperty CShareMgr *shareMgr;
StrongProperty CSharePersonMgr *personMgr;
StrongProperty NSURL *videoUrl;
StrongProperty UIScrollView *scrollView;
@property(nonatomic)BOOL isshowDelBtn;
@property(nonatomic,strong)WZPlayerViewController *player;
@property (nonatomic,strong)UIImage *videoImage;
@end

@implementation EFengComposeController


- (UIScrollView *)scrollView
{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.backgroundColor = ClearColor;
        _scrollView.pagingEnabled = NO;
        _scrollView.bounces = YES;
        _scrollView.delegate = self;
        _scrollView.scrollEnabled = YES;
    }
    return _scrollView;
}
-(void)setVideoUrl:(NSURL *)videoUrl
{
    if (_videoUrl != nil) {
        NSString *filePath = [[_videoUrl absoluteString] stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSError *error = nil;
            [fileManager removeItemAtPath:filePath error:&error];
            
            if (error) {
                NSLog(@"deleteAllVideo删除视频文件出错:%@", error);
            }
        }
        [self.player removeFromParentViewController];
        [self.player.view removeFromSuperview];
        self.player = nil;
    }
    _videoUrl = videoUrl;
    self.videoImage = [self thumbnailImageForVideo:_videoUrl atTime:0];
    if (self.videoImage) {
        [self.photosArray addObject:self.videoImage];
    }
    [self reDisplayPhotosView];
}

- (NSMutableArray *)photosArray
{
    if (_photosArray == nil) {
        _photosArray = [NSMutableArray array];
    }
    return _photosArray;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:composeSendTagOfEmotionIcon object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:composeDeleteTagOfEmotionIcon object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.isshowDelBtn = NO;
    self.view.backgroundColor = RGBCOLOR(243, 243, 243);
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.title = @"分享";
    self.curContact = [[[CContactMgr alloc] init] loadCurContact];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteEmotionStr) name:composeDeleteTagOfEmotionIcon object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addEmotionStr:) name:composeSendTagOfEmotionIcon object:nil];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"发布" target:self sel:@selector(composeShare) titleFont:Font18 titleColor:WhiteColor];
    UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
    btn.enabled = NO;
    
    self.shareMgr = [[CShareMgr alloc] init];
    self.personMgr = [[CSharePersonMgr alloc] init];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didtap)];
    [self.view addGestureRecognizer:tap];
    
    self.scrollView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 44.0f - StatusBarHeight);
    [self.view addSubview:self.scrollView];
    //创建工具菜单
    [self setupToolBar];
    
    //创建输入框
    EFengComposeTextView *textView = [[EFengComposeTextView alloc] init];
    textView.frame = CGRectMake(0.0f, CGRectGetMaxY(self.toolBar.frame) + 10.0f, HARDWARE_SCREEN_WIDTH, 200.0f);
    textView.layer.borderWidth = 0.5f;
    textView.layer.borderColor = RGBCOLOR(0xd4, 0xd4, 0xd4).CGColor;
    textView.layer.cornerRadius = 2.5f;
    textView.eFengComposeTextViewDelegate = self;
    textView.textFont = Font18;
    //bug 9479 fixed by lixu
    [textView setMAXCHARACTERCOUNT:3000];
    [textView setPlaceHoldText:@"分享你此时此刻的精彩..."];
    textView.backgroundColor = WhiteColor;
    textView.userInteractionEnabled = YES;
    [self.scrollView addSubview:textView];
    self.textView = textView;
    
    //创建PhotosView
    UIView *photosView = [[UIView alloc] init];
    
    photosView.frame = CGRectMake(0.0f, CGRectGetMaxY(self.textView.frame), HARDWARE_SCREEN_WIDTH - 20.0f, HARDWARE_SCREEN_HEIGHT - 44.0f - StatusBarHeight - CGRectGetMaxY(self.textView.frame));
    photosView.backgroundColor = ClearColor;
    [self.scrollView addSubview:photosView];
    self.photosView = photosView;
    EFComposeEmotionView *emo = [EFComposeEmotionView defaultComposeEmotionView];
    emo.eFComposeEmotionViewDelegatedelegate = self;
    [self.view addSubview:emo];
    CGRect emoFrame = emo.frame;
    emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 44.0f - StatusBarHeight;
    [emo setFrame:emoFrame];
    [self.view bringSubviewToFront:emo];
    self.composeEmotionView = emo;
    
}
- (void)setupToolBar
{
    
    UIView *toolBar = [[UIView alloc] init];
    toolBar.backgroundColor = WhiteColor;
    toolBar.frame = CGRectMake(0, 10.0f, HARDWARE_SCREEN_WIDTH, 50.0f);
    [self.scrollView addSubview:toolBar];
    self.toolBar = toolBar;
    
    UIButton *emotionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [emotionButton setImage:[UIImage imageNamed:@"smile"] forState:UIControlStateNormal];
    [emotionButton setImage:[UIImage imageNamed:@"smile-click"] forState:UIControlStateHighlighted];
    [emotionButton addTarget:self action:@selector(emotionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:emotionButton];
    self.emotionButton = emotionButton;
    
    UIButton *pictureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [pictureButton setImage:[UIImage imageNamed:@"icon-picDefault"] forState:UIControlStateNormal];
    [pictureButton setImage:[UIImage imageNamed:@"icon-picClick"] forState:UIControlStateHighlighted];
    [pictureButton addTarget:self action:@selector(pictureButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:pictureButton];
    self.pictureButton = pictureButton;
    UIButton *videoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoButton setImage:[UIImage imageNamed:@"shipinclick"] forState:UIControlStateHighlighted];
    [videoButton setImage:[UIImage imageNamed:@"shipin"] forState:UIControlStateNormal];
    [videoButton addTarget:self action:@selector(videoButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:videoButton];
    self.videoButton = videoButton;
    
    
    //    UIButton *quanxianButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //    quanxianButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //    quanxianButton.titleLabel.font = Font17;
    //    [quanxianButton setTitle:@"[所有人可见]" forState:UIControlStateNormal];
    //    [quanxianButton  setTitleColor:RGBCOLORWITH16COLOR(0x369bdf) forState:UIControlStateNormal];
    //    [quanxianButton addTarget:self action:@selector(quanxianButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [toolBar addSubview:quanxianButton];
    //    self.quanxianButton = quanxianButton;
    
    self.emotionButton.frame = CGRectMake(0, 0, self.toolBar.height, self.toolBar.height);
    self.pictureButton.frame = CGRectMake(CGRectGetMaxX(self.emotionButton.frame), 0, self.toolBar.height, self.toolBar.height);
    self.videoButton.frame = CGRectMake(CGRectGetMaxX(self.pictureButton.frame), 0, self.toolBar.height, self.toolBar.height);
    //    self.quanxianButton.frame = CGRectMake(self.toolBar.width - 10.0f - 100.0f, 0, 100.0f, self.toolBar.height);
    
}

-(void)back
{
    [_textView endEditing:YES];
    
    
    if (self.photosArray.count <= 0 && self.textView.text.length <= 0&&self.videoUrl == nil) {
        [self.navigationController popViewControllerAnimated:YES];
    } else{
        __block EFengComposeController *block = self;
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"您分享的内容还没有发布，是否退出编辑?"];
        [alert addButton:Button_OK withTitle:@"是" handler:^(JKAlertDialogItem *item) {
            [block deleteVideo];
            [block.navigationController popViewControllerAnimated:YES ];
            
        }];
        
        [alert addButton:Button_CANCEL withTitle:@"否" handler:^(JKAlertDialogItem *item) {
            
            
        }];
        [alert show];
    }
}
-(void)videoButtonClick:(UIButton*)btn
{
    CaptureViewController *captureViewCon = [[CaptureViewController alloc] initWithNibName:@"CaptureViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    captureViewCon.URLBlock = ^(NSURL *url){
        weakSelf.videoUrl = url;
    };
    [self presentViewController:captureViewCon animated:YES completion:nil];
}

- (void)emotionButtonClick:(UIButton *)btn
{
    self.isshowDelBtn = NO;
    [self reDisplayPhotosView];
    if (self.textView.isFirstResponder) {
        [self.textView resignFirstResponder];
    }
    
    
    if (self.isEmotionShow) {       //消失
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = self.composeEmotionView.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
        
        
        
        [self.composeEmotionView setFrame:emoFrame];
        
        [UIView commitAnimations];
        
    }
    else            //出现
    {
        if (M_ISSTRNULL(self.textView.text)) {
            self.textView.selectedRange = NSMakeRange(0, 0);
        }
        CGRect emoFrame = self.composeEmotionView.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 180.0f - 64.0f;
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        [self.composeEmotionView setFrame:emoFrame];
        
        [UIView commitAnimations];
        
    }
    self.isEmotionShow = !self.isEmotionShow;
    
}

- (void)pictureButtonClick:(UIButton *)btn
{
    self.isshowDelBtn = NO;
    [self reDisplayPhotosView];
    if (self.isEmotionShow) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = self.composeEmotionView.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
        [self.composeEmotionView setFrame:emoFrame];
        
        [UIView commitAnimations];
    }
    
    self.isEmotionShow = NO;
    if ([self.textView isFirstResponder]) {
        [self.textView resignFirstResponder];
    }
    
    RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{
        
    }];
    
    __block EFengComposeController *block = self;
    RIButtonItem *photoItem = [RIButtonItem itemWithLabel:@"拍照" action:^{
        [block takePhotosWithCamera];
    }];
    
    RIButtonItem *selectItem = [RIButtonItem itemWithLabel:@"从相册选择" action:^{
        [block selectPicFromAlbum];
    }];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil cancelButtonItem:cancelItem destructiveButtonItem:selectItem otherButtonItems:photoItem, nil];
    [actionSheet showInView:self.view];
    
}

-(void)selectPicFromAlbum
{
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 9 - self.photosArray.count;
    imagePickerController.maxSelectedCount = 9;
    imagePickerController.previewText = @"预览";
    imagePickerController.oprationText = @"确定";
    //  CHSNavigationController *navigationController = [[CHSNavigationController alloc] initWithRootViewController:imagePickerController];
    [self.navigationController pushViewController:imagePickerController animated:YES];//:navigationController animated:YES completion:NULL];
    //[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    //    }];
}

-(void)takePhotosWithCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        [imagePickerController setDelegate:self];
        [imagePickerController setEditing:YES];
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }else
    {
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.maximumNumberOfSelection = 9 - self.photosArray.count;
        imagePickerController.maxSelectedCount = 9;
        imagePickerController.previewText = @"预览";
        imagePickerController.oprationText = @"确定";
        
        [self.navigationController pushViewController:imagePickerController animated:YES];
    }
    
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *camaerImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *origImage = [UIImage fixOrientation:camaerImage];
    [self.photosArray addObject:origImage];
    [self reDisplayPhotosView];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfos:(id)info
{
    if (imagePickerController.allowsMultipleSelection) {
        NSArray *mediaInfoArray = (NSArray *)info;
        NSInteger count = mediaInfoArray.count;
        for (int i = 0; i < count; i++) {
            NSMutableDictionary *aDic = [mediaInfoArray objectAtIndex:i];
            UIImage *aImg = [aDic objectForKey:@"UIImagePickerControllerOriginalImage"];
            UIImage *origImage = [UIImage fixOrientation:aImg];
            [self.photosArray addObject:origImage];
            [self reDisplayPhotosView];
        }
        
    }
}

- (void)reDisplayPhotosView
{
    if (self.photosArray.count <= 0 && self.textView.text.length <= 0&&self.videoUrl == nil) {
        UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        btn.enabled = NO;
    } else {
        UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        btn.enabled = YES;
        
    }
    [self.photosView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat gap = 10.0f;
    if (self.photosArray.count > 0) {
        self.pictureButton.enabled = YES;
        self.videoButton.enabled = NO;
        for (int i = 0; i < self.photosArray.count; i ++) {
            UIImage *image = self.photosArray[i];
            EFengComposePhotoView *photo = [[EFengComposePhotoView alloc] init];
            photo.delButton.hidden = !_isshowDelBtn;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBigPic:)];
            [photo addGestureRecognizer:tap];
            
            UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showShanChuLongPress:)];
            
            [photo addGestureRecognizer:longTap];
            
            photo.tag = i;
            x = i % 3 * (PHOTOWIDTH + gap) + 30.0f;
            y = i / 3 * (PHOTOWIDTH + gap) + 10.0f;
            photo.frame = CGRectMake(x, y, PHOTOWIDTH, PHOTOWIDTH);
            photo.eFengComposePhotoViewDelegate = self;
            photo.image = [UIImage scaleShareImageFromImage:image scaledToWidth:PHOTOWIDTH];
            [self.photosView addSubview:photo];
        }
        self.photosView.height = (self.photosArray.count / 3 + 1) * PHOTOWIDTH + self.photosArray.count / 3 * gap + 20.0f;
        self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.photosView.frame));
    }
    if (self.videoUrl != nil)
    {
        for (id view in self.photosView.subviews) {
            if ([view isKindOfClass:[EFengComposePhotoView class]]) {
                [view removeFromSuperview];
            }
        }
        self.player = [[WZPlayerViewController alloc]initWithVideoFileURL:_videoUrl AndViewFrame:CGRectMake(10, CGRectGetMaxY(self.textView.frame) + 10.0f, HARDWARE_SCREEN_WIDTH-20, 250.0f)];
        [self addChildViewController:_player];
        [self.scrollView addSubview:_player.view];
        self.pictureButton.enabled = NO;
        self.videoButton.enabled = YES;
        
    }
}


- (void)showShanChuLongPress:(UILongPressGestureRecognizer *)longPress
{
    if(longPress.state != UIGestureRecognizerStateBegan || [self becomeFirstResponder])
        return;
    self.isshowDelBtn = YES;
    for (EFengComposePhotoView *photo in self.photosView.subviews) {
        photo.delButton.hidden = !_isshowDelBtn;
    }
}
- (void)showBigPic:(UITapGestureRecognizer *)tap
{
    MJPhotoBrowser *photoBrower = [[MJPhotoBrowser alloc] init];
    NSMutableArray *photos = [NSMutableArray array];
    
    int i = 0;
    for (UIImage *image in self.photosArray) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.image = image;
        photo.srcImageView = self.photosView.subviews[i];
        [photos addObject:photo];
        i ++;
    }
    photoBrower.photos = photos;
    photoBrower.currentPhotoIndex = tap.view.tag;
    [photoBrower show];
}
- (void)eFengComposePhotoViewDidClickDeleteWithPhotoTag:(NSInteger)tag
{
    [self.photosArray removeObjectAtIndex:tag];
    if (self.photosArray.count == 0) {
        self.isshowDelBtn = NO;
    }
    [self reDisplayPhotosView];
}
//- (void)quanxianButtonClick:(UIButton *)btn
//{
//    RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{
//
//    }];
//
//    __block EFengComposeController *block = self;
//
//    RIButtonItem *allItem = [RIButtonItem itemWithLabel:@"所有人可见" action:^{
//
//    }];
//    RIButtonItem *depItem = [RIButtonItem itemWithLabel:@"指定部门可见" action:^{
////        EFengShareSelectDepController *dep = [[EFengShareSelectDepController alloc] initWithDepartId:@""];
////        [self presentViewController:dep animated:YES completion:nil];
//    }];
//    RIButtonItem *groupItem = [RIButtonItem itemWithLabel:@"指定群可见" action:^{
//
//    }];
//    RIButtonItem *memItem = [RIButtonItem itemWithLabel:@"指定人员可见" action:^{
//
//    }];
//
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil cancelButtonItem:cancelItem destructiveButtonItem:nil otherButtonItems:allItem,depItem,groupItem,memItem, nil];
//    [actionSheet showInView:self.view];
//
//
//}

- (void)composeShare
{
    //    __block EFengComposeController *weak = self;
    
    NSString *type = nil;
    if (self.photosArray.count > 0 && self.textView.text.length <= 0&&self.videoUrl == nil) {
        type = @"img";
    } else if (self.photosArray.count > 0 && self.textView.text.length > 0&&self.videoUrl == nil){
        type = @"textimg";
    } else if(self.videoUrl!=nil){
        type = @"video";
    }else {
        type = @"text";
    }
    
    CServerSettingModel *serverSetting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    NSString *timeStamp = [UIUtil getCurrentTimeStamp];
    NSString *idkey = serverSetting.yuLiuZiduan1;
    if (M_ISSTRNULL(idkey)) {
        idkey = @"111111";
    }
    NSString *idStr = [NSString stringWithFormat:@"%@%@",timeStamp,idkey];
    
    __block EFengComposeController *weakSelf = self;
    __block EFengShare *share = [[EFengShare alloc] init];
    share.shareId = idStr;
    share.content = self.textView.text;
    share.releaseUserId = self.curContact.UserID;
    share.releaseUserName = self.curContact.UserName;
    share.releaseType = type;
    NSMutableArray *photoArrayM = [NSMutableArray array];
    NSMutableArray *videoArrayM = [NSMutableArray array];
    if (self.photosArray.count > 0) {
        for (int i = 0; i <self.photosArray.count; i ++) {
            NSString *fileName = [NSString stringWithFormat:@"%@___%@___%zd.jpg",self.curContact.UserID,timeStamp,i];
            UIImage *image = self.photosArray[i];
            [[SDWebImageManager sharedManager].imageCache storeImage:image forKey:fileName];
            [[ChildHoodService defaultService] savePersonalUpLoadImageWithFileName:fileName content:UIImageJPEGRepresentation(image,1) userId:self.curContact.UserID];

            NSDictionary *dict = @{@"url_max":fileName,@"url_min":fileName};
            [photoArrayM addObject:dict];
        }
        
    }
    if (self.videoUrl) {
        NSString *fileName = [NSString stringWithFormat:@"%@___%@.mp4",self.curContact.UserID,timeStamp];
        NSData *data = [NSData dataWithContentsOfURL:self.videoUrl];
        NSDictionary *dict = @{@"video":fileName,@"length":@(data.length)};
        [videoArrayM addObject:dict];
        [[ChildHoodService defaultService] savePersonalUpLoadVideoWithFileName:fileName content:data userId:self.curContact.UserID];
    }
    share.date = timeStamp;
    share.yuLiuZiduan2 = 1;
    share.imageName = [photoArrayM copy];
    share.videoName = [videoArrayM copy];
    share.isRead = YES;
    share.isClick = YES;
    share.isShowShanchu = YES;
    [self.shareMgr insertWithShare:share];
    [self.personMgr insertWithShare:share];
    //        [[CXmppRequestMgr shareInstance] composeShareWithContact:self.curContact shareId:idStr content:self.textView.text type:type imageArray:self.photosArray visibleUserId:@"all" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
    //            if ([responseObject[@"result"] isEqualToString:@"success"]) {
    //                share.date = [NSString stringWithFormat:@"%@",responseObject[@"date"]];
    //                share.shareId = [NSString stringWithFormat:@"%@",responseObject[@"id"]];
    //                [weakSelf.shareMgr updateShareWithShareId:share.shareId date:share.date];
    //                [weakSelf.personMgr updateShareWithShareId:share.shareId date:share.date];
    //                [USER_DEFAULT setBool:YES forKey:@"sendOK"];
    //                [USER_DEFAULT synchronize];
    //            }
    //        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
    //
    //        }];
    NSData *data = [NSData dataWithContentsOfURL:self.videoUrl];
    [[CXmppRequestMgr shareInstance] composeShareWithContact:self.curContact sharId:idStr content:self.textView.text type:type imageArray:self.photosArray videoData:data visibleUseId:@"all" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"success"]) {
            share.date = [NSString stringWithFormat:@"%@",responseObject[@"date"]];
            share.shareId = [NSString stringWithFormat:@"%@",responseObject[@"id"]];
            [weakSelf.shareMgr updateShareWithShareId:share.shareId date:share.date];
            [weakSelf.personMgr updateShareWithShareId:share.shareId date:share.date];
            [weakSelf deleteVideo];
            [USER_DEFAULT setBool:YES forKey:@"sendOK"];
            [USER_DEFAULT synchronize];
        }
        
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:IMDIDCOMPOSESHARE object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didtap
{
    self.isshowDelBtn = NO;
    //    [self reDisplayPhotosView];
    if (self.isEmotionShow) {
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = self.composeEmotionView.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
        
        
        
        [self.composeEmotionView setFrame:emoFrame];
        
        [UIView commitAnimations];
    }
    
    self.isEmotionShow = NO;
    if ([self.textView isFirstResponder]) {
        [self.textView resignFirstResponder];
    }
}

-(void)addEmotionStr:(NSNotification *)notification
{
    NSString *str = (NSString*)notification.object;
    if (!self.textView.text) {
        self.textView.text = @"";
    }
    
    NSRange tempRange = [self.textView selectedRange];
    if (self.selectedRange.location<tempRange.location && self.selectedRange.location!=0) {
        tempRange = self.selectedRange;
    }
    
    
    
    NSString *firstStr = [self.textView.text substringToIndex:tempRange.location];
    NSString *lastStr =[self.textView.text substringFromIndex:tempRange.location];
    
    NSString *new_str = [NSString stringWithFormat:@"%@%@%@",firstStr,str,lastStr];
    NSRange range = NSMakeRange([[NSString stringWithFormat:@"%@%@",firstStr,str] length], 1);
    self.selectedRange = range;
    
    [self.textView setText:new_str];
    [self eFengComposeTextViewDidChange:self.textView];
    
}

- (void)deleteEmotionStr{
    if ([self.textView.text length]>2) {
        NSMutableString *str =[NSMutableString stringWithString:self.textView.text];
        if ([[str substringFromIndex:[str length]-1] isEqualToString:@"]"]) {
            [str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
            for (int index=0; index<[self.textView.text length]-1; index++) {
                if (![[str substringFromIndex:[str length]-1] isEqualToString:@"["]) {
                    if ([[str substringFromIndex:[str length]-1] isEqualToString:@"]"]) {
                        break;
                    }
                    [str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
                }else {
                    [str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
                    [self.textView setText:str];
                    [self eFengComposeTextViewDidChange:self.textView];
                    break;
                }
                
            }
            
        }
    }
}



#pragma mark

- (void)eFengComposeTextViewDidChange:(EFengComposeTextView *)textView
{
    if (self.photosArray.count <= 0 && self.textView.text.length <= 0) {
        UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        btn.enabled = NO;
    } else {
        UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        btn.enabled = YES;
        
    }
    
}

- (void)eFengComposeTextViewDidBeginEditing:(EFengComposeTextView *)textView
{
    self.isshowDelBtn = NO;
    [self reDisplayPhotosView];
    
    if (self.isEmotionShow) {
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = self.composeEmotionView.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
        
        
        [self.composeEmotionView setFrame:emoFrame];
        
        [UIView commitAnimations];
    }
    
    self.isEmotionShow = NO;
    self.selectedRange = NSMakeRange(0, 0);
    if (M_ISSTRNULL(textView.text)) {
        textView.selectedRange = NSMakeRange(0, 0);
    }
}

- (void)eFComposeEmotionViewViewDidSure
{
    if (self.isEmotionShow) {
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        CGRect emoFrame = self.composeEmotionView.frame;
        emoFrame.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
        
        
        [self.composeEmotionView setFrame:emoFrame];
        
        [UIView commitAnimations];
    }
    
    self.isEmotionShow = NO;
    
}
//获取首桢图片
-(UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}
-(void)deleteVideo
{
    if (self.videoUrl) {
        NSString *filePath = [[_videoUrl absoluteString] stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSError *error = nil;
            [fileManager removeItemAtPath:filePath error:&error];
            
            if (error) {
                NSLog(@"deleteAllVideo删除视频文件出错:%@", error);
            }
        }
        
    }
}
@end
